import React, {PureComponent} from "react";
import FormEditor from '../../components/FormEditor';
import {
    calculateFee,
    calculateOutFee,
    clearFee,
    clearVehicleFee,
    findFeesByClientId,
    getBaoGuanFeeByClientId,
    getClientList2,
    getLines,
    getVehicleFee,
    updateOrderModel,
    updateVehicleFees
} from "./actions";
import {connect} from "react-redux";
import {getPrincipal} from "../../lib/identity";
import {formatDate} from "../../lib/func";

class OrderInfoModal extends PureComponent {

    state = {pickLines: [], deliveryLines: []};

    handleUpdateGhOrderModel = order => {
        const {dispatch, model, lines = [], vehicleFees, outFees = [], vehicles = [], calculateType} = this.props;
        if (order.organizationId) {
            dispatch(getClientList2(order.organizationId));
        } else {
            dispatch(getClientList2('null'));
        }
        dispatch(getLines({...order}));
        if (order.clientId !== model.clientId) {
            delete order.originDestPlace;
            delete model.originDestPlace;
            delete model.carrierDeparturePort;
            dispatch(findFeesByClientId(order.clientId));
            dispatch(getBaoGuanFeeByClientId(order.clientId));
            dispatch(getVehicleFee({"ownerId": order.clientId}));
        }
        if (order.originDestPlace && order.originDestPlace.length > 0) {
            const arr = order.originDestPlace.split("-");
            order.originPlace = arr[0];
            order.destPlace = arr[1];
            const found = lines.find(item => item.originPlace === order.originPlace &&
                item.destPlace === order.destPlace && item.calculateType === order.calculateType);
            if (found) {
                order.pb = found.pb;
                order.pbText = "1:" + found.pb;
            }
            if (found && order.carrierDeparturePort === undefined) {
                order.carrierDeparturePort = found.departurePort;
            }
        } else {
            order.originPlace = null;
            order.destPlace = null;
        }
        if (order.deliveryModel && order.deliveryModel.length > 0) {
            const found = vehicleFees.find(item => item.name === order.deliveryModel);
            if (found) {
                order.deliveryModelFee = found.amount;
            }
        }
        if (order.squareNumber && order.pb) {
            order.volumeWeight = (order.squareNumber * order.pb).toFixed(2);
        }
        // 计算应收
        if (order.clientId && order.businessCode && order.calculateType && order.originPlace && order.destPlace && order.pickDate) {
            // 转换计费方式
            let calculateTypeStr = order.calculateType;
            for (let i = 0; i < calculateType.length; i++) {
                if (calculateType[i]['label'] === order.calculateType) {
                    calculateTypeStr = calculateType[i]['value'];
                    break
                }
            }
            order.noTips = true;
            order.calculateTime = formatDate(order.pickDate);
            // 清空应付的费用，重新计算
            dispatch(clearFee());
            dispatch(calculateFee({...order, "ghOrder": true, calculateType: calculateTypeStr}));
            // 重新刷新应付费用，只有费用小于等于0才会触发修改，这样做的目的是如果某一个费用因为某些原因修改了，但是在编辑订单是会触发二次计费，会把前面手动更改的覆盖
            outFees.forEach(item => {
                if (item.carrierId) {
                    dispatch(calculateOutFee({
                        ...order, ...item,
                        "noTips": true,
                        "ghOrder": true,
                        calculateType: calculateTypeStr
                    }));
                }
            });
        }
        // 更新车型费用
        const vehicleFound = vehicles.find(item => item.name === order.deliveryModel);
        if (vehicleFound) {
            dispatch(updateVehicleFees({
                frontPickFee: vehicleFound.frontPickFee,
                deliveryFee: vehicleFound.deliveryFee
            }));
        }
        dispatch(updateOrderModel({
            ...model, ...order,
            "deliveryLine": model.deliveryLine,
            "vehicleLine": model.vehicleLine,
            "id": model.id
        }));
    };

    changeClient = clientId => {
        const {dispatch} = this.props;
        dispatch(getVehicleFee({"ownerId": clientId}));
    };

    changeVehicleType = vehicleName => {
        const {dispatch, vehicles, model} = this.props;
        const pickLines = [];
        vehicles.forEach(item => {
            if (item.name === vehicleName) {
                pickLines.push({...item});
            }
        });
        dispatch(updateOrderModel({...model}));
        this.setState({pickLines: pickLines});
    };

    changePickLine = line => {
        const {dispatch, model} = this.props;
        if (line) {
            const lineArray = line.split("-");
            const start = lineArray[0];
            const end = lineArray[1];
            const found = this.state.pickLines.find(item => item.name === model.vehicleType && item.startPlace === start && item.endPlace === end);
            if (found) {
                model.vehicleLine = found.startPlace + "-" + found.endPlace;
                dispatch(updateVehicleFees({"feeName": "提货费", "feeCount": found.amount}));
                dispatch(updateOrderModel({...model}));
            }
        } else {
            model.vehicleLine = null;
            dispatch(updateOrderModel({...model}));
            dispatch(clearVehicleFee("提货费"));
        }
    };

    changeDeliveryModel = vehicleName => {
        const {vehicles} = this.props;
        const deliveryLines = [];
        vehicles.forEach(item => {
            if (item.name === vehicleName) {
                deliveryLines.push(item);
            }
        });
        this.setState({deliveryLines: deliveryLines});
    };

    changeDeliveryLine = line => {
        const {dispatch, model} = this.props;
        if (line) {
            const lineArray = line.split("-");
            const start = lineArray[0];
            const end = lineArray[1];
            const found = this.state.deliveryLines.find(item => item.name === model.deliveryModel && item.startPlace === start && item.endPlace === end);
            if (found) {
                model.deliveryLine = found.startPlace + "-" + found.endPlace;
                dispatch(updateVehicleFees({"feeName": "派送费", "feeCount": found.amount}));
                dispatch(updateOrderModel({...model}));
            }
        } else {
            model.deliveryLine = null;
            dispatch(updateOrderModel({...model}));
            dispatch(clearVehicleFee("派送费"));
        }
    };

    render() {
        const {model, clientList, organizations, businessCodeList, calculateType, lines, vehicles} = this.props;
        const originDestPlaceList = [];
        lines.forEach(item => {
            const originDestPlace = item.originPlace + "-" + item.destPlace;
            const found = originDestPlaceList.find(item => item.value === originDestPlace);
            if (!found) {
                originDestPlaceList.push({label: originDestPlace, value: originDestPlace});
            }
        });
        if (model.originPlace && model.destPlace) {
            model.originDestPlace = model.originPlace + "-" + model.destPlace;
        }
        const selectVehicleOptions = [];
        vehicles.forEach(item => {
            const found = selectVehicleOptions.find(o => o.name === item.name);
            if (!found) {
                selectVehicleOptions.push({...item});
            }
        });
        const pickLines = this.state.pickLines || [];
        pickLines.forEach(item => {
            item.showName = item.startPlace + "-" + item.endPlace;
        });
        const deliveryLines = this.state.deliveryLines || [];
        deliveryLines.forEach(item => {
            item.showName = item.startPlace + "-" + item.endPlace;
        });
        if (model.pb) {
            model.pbText = "1:" + model.pb;
        }
        if (model.volumeWeight) {
            model.volumeWeight = parseFloat((model.volumeWeight || 0)).toFixed(3);
        }
        if (model.squareNumber) {
            model.squareNumber = parseFloat((model.squareNumber || 0)).toFixed(4);
        }
        // 检查是否有费用锁定
        let feeHasLock = false;
        model.feeList && model.feeList.forEach(item => {
            if (item.status === "LOCK") {
                feeHasLock = true;
            }
        });
        const schema = [
            {
                title: '基础信息',
                fields: [
                    {
                        field: 'clientId',
                        title: '客户',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: clientList,
                            labelField: "name",
                            valueField: "id",
                            onChange: this.changeClient
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择客户'}]
                        }
                    }, {
                        field: 'businessCode',
                        title: '业务类型',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: businessCodeList,
                            labelField: "name",
                            valueField: "name"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择业务类型'}]
                        }
                    }, {
                        field: 'calculateType',
                        title: '计费方式',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: calculateType
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择计费方式'}]
                        }
                    }, {
                        field: 'bookNumber',
                        title: '订舱号',
                        readonly: feeHasLock,
                        type: 'text',
                        fieldOptions: {
                            rules: [{required: true, message: '请选择订舱号'}]
                        }
                    }, {
                        field: 'pickDate',
                        title: '提货日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }, {
                        field: 'actDepartureTime',
                        title: '发车日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }, {
                        field: 'quantity',
                        title: '数量',
                        readonly: feeHasLock,
                        type: 'number'
                    }, {
                        field: 'squareNumber',
                        title: '方数(m³)',
                        readonly: feeHasLock,
                        type: 'number'
                    }, {
                        field: 'grossWeight',
                        title: '毛重(KG)',
                        readonly: feeHasLock,
                        type: 'number'
                    }, {
                        field: 'pbText',
                        title: '重泡比',
                        readonly: true
                    }, {
                        field: 'volumeWeight',
                        title: '体积重(KG)',
                        readonly: true
                    }, {
                        field: 'originDestPlace',
                        title: '线路',
                        readonly: feeHasLock,
                        type: 'listSelector',
                        controlProps: {
                            dataSource: originDestPlaceList
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择线路'}]
                        }
                    }
                ]
            }, {
                title: '提货信息',
                fields: [
                    {
                        field: 'vehicleType',
                        title: '提货车型',
                        readonly: feeHasLock,
                        type: 'listSelector',
                        controlProps: {
                            dataSource: selectVehicleOptions,
                            labelField: "name",
                            valueField: "name",
                            onChange: this.changeVehicleType
                        }
                    }, {
                        field: 'vehicleLine',
                        title: '提货线路',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: pickLines,
                            labelField: "showName",
                            valueField: "showName",
                            onChange: this.changePickLine
                        }
                    }
                ]
            }, {
                title: '派送信息',
                fields: [
                    {
                        field: 'deliveryModel',
                        title: '派送车型',
                        readonly: feeHasLock,
                        type: 'listSelector',
                        controlProps: {
                            dataSource: selectVehicleOptions,
                            labelField: "name",
                            valueField: "name",
                            onChange: this.changeDeliveryModel
                        }
                    }, {
                        field: 'deliveryLine',
                        title: '派送线路',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: deliveryLines,
                            labelField: "showName",
                            valueField: "showName",
                            onChange: this.changeDeliveryLine
                        }
                    }, {
                        field: 'deliveryModelRemark',
                        title: '派送备注',
                        readonly: feeHasLock,

                    }, {
                        field: 'receiveDate',
                        title: '派送日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }
                ]
            }, {
                title: '备注信息',
                fields: [
                    {
                        field: 'remark',
                        title: '备注',
                        type: 'textArea',
                        readonly: feeHasLock

                    }
                ]
            }
        ];
        if (getPrincipal().admin) {
            schema[0].fields.splice(0, 0, {
                field: 'organizationId',
                title: '所属机构',
                type: 'treeSelector',
                readonly: feeHasLock,
                controlProps: {
                    treeData: organizations,
                    labelField: "name",
                    valueField: "id",
                    treeCheckable: false
                },
                fieldOptions: {
                    rules: [{required: true, message: '请选择所属机构'}]
                }
            });
        }
        return (

            <FormEditor
                schema={schema}
                column={3}
                showActionBar={false}
                defaultValues={model}
                onChange={this.handleUpdateGhOrderModel}
            />
        );
    }
}

const mapStateToProps = state => {
    return {
        clientList: state.ghOrder.list.clientList,
        carrierList: state.home.carriers,
        currencyList: state.ghOrder.list.currencyList,
        businessCodeList: state.ghOrder.list.businessCodeList,
        calculateType: state.common.calculateType,
        transportTypeList: state.ghOrder.list.transportTypeList,
        organizations: state.home.organizations,
        vehicles: state.ghOrder.list.vehicles,
        vehicleFees: state.ghOrder.orderFee.vehicleFees,
        outFees: state.ghOrder.orderOutFee.feeList,
        lines: state.ghOrder.lines.lines
    };
};

export default connect(mapStateToProps)(OrderInfoModal);
